import * as ResourceService from '../services/Editor/resource';

export default {
    namespace: 'preview',
    state: {},
    reducers: {
        save(state, { payload: preview }) {
            return { ...state, ...preview };
        },
    },
    effects: {
        *previewQRcode({ payload: query }, { put, call, select }) {
            const fetched = yield select(state => state.preview.fetched);
            if (!fetched) {
                const { data: preview } = yield call(ResourceService.previewQRcode, {});
                preview.fetched = true;
                yield put({
                    type: 'save',
                    payload: preview,
                });
            }
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname, query }) => {
                if (pathname.indexOf('/preview')!==-1) {
                    dispatch({ type: 'previewQRcode', payload: query });
                }
            });
        },
    },
};
